//
//  SyncManager.m
//  i18n
//
//  Created by Earus on 11/29/11.
//  Copyright (c) 2011 patrick.decaluwe@student.uclouvain.be. All rights reserved.
//

#import "SyncManager.h"

@implementation SyncManager

@synthesize uiView;

-(id)initWithUIView:(UIView*)aUiView
{
    self.uiView = aUiView;
    return self;
}

-(void)sync
{
    NSString *file;
	NSString *docsDir = [[NSString alloc] initWithFormat: @"%@/Documents", NSHomeDirectory()];
    NSError* error = nil;
	NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:docsDir];
    NSMutableString *apiUrl = [[NSMutableString alloc] initWithString:@"http://i18n.ohmyenglish.co.kr/php/sync_xml.php?member_srl="];
    NSMutableString *fileNames = [[NSMutableString alloc] init];
    NSMutableString *fileDates = [[NSMutableString alloc] init];
	
    [apiUrl appendString:[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"]];
    
	while ((file = [dirEnum nextObject])) {
        NSDictionary* properties = [[NSFileManager defaultManager]
                                    attributesOfItemAtPath:[[NSString alloc] initWithFormat:@"%@/%@", docsDir, file]
                                    error:&error];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YMMddhhmmss"];
        
        [fileNames appendString:[NSString stringWithFormat:@"%@,", file]];            
        [fileDates appendString:[NSString stringWithFormat:@"%@,",[dateFormatter stringFromDate:[properties objectForKey:NSFileModificationDate]]]];
	}
    
    if ([fileNames length] == 0)
        return;

    [fileNames deleteCharactersInRange:NSMakeRange([fileNames length] - 1, 1)];
    [fileDates deleteCharactersInRange:NSMakeRange([fileDates length] - 1, 1)];

    [apiUrl appendString:@"&filenames="];
    [apiUrl appendString:fileNames];
    [apiUrl appendString:@"&timestamps="];
    [apiUrl appendString:fileDates];
    
    NSLog(@"apiUrl = %@", apiUrl);
    
    loader = [[DataLoader alloc] initWithTag:@"sync"
                                         url:apiUrl
                                    delegate:self
                                   superView:self.uiView];
}

# pragma mark Implements Protocols

- (void)dataLoader:(DataLoader *)loader didFinishWithData:(NSMutableData *)data tag:(NSString *)tag
{
    NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    [parser setDelegate:self];
    [parser parse];
}

-(void)getXMLFrom:(NSString*)url {
	if( httpManager ) {
		[httpManager release];
		httpManager = nil;
	}
	
	httpManager = [[HttpManager alloc] initWithUrl:url delegate:self];
}

- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict {  

    if ([elementName isEqualToString:@"DOWNLOAD_LIST"]) {
        isDownloadMode = YES;
    }
    
    if ([elementName isEqualToString:@"UPLOAD_LIST"]) {
        isDownloadMode = NO;
    }
    
    if ([elementName isEqualToString:@"FILE"]) {
        if (isDownloadMode == YES) {
			NSLog(@"%@", [attributeDict objectForKey:@"url"]);
			[self getXMLFrom:[attributeDict objectForKey:@"url"]];
			downloadURL = [attributeDict objectForKey:@"url"];
			NSLog(@"Download Started %@", downloadURL);
        } else {
            // TODO: 여기서 파일 업로드
            NSString *urlString = @"http://i18n.ohmyenglish.co.kr/php/upload_file.php?member_srl=10027";
            NSString *docsDir = [[NSString alloc] initWithFormat: @"%@/Documents", NSHomeDirectory()];
            NSString *filename = [NSString stringWithFormat:@"%@/%@", docsDir, [attributeDict objectForKey:@"url"]];
            NSMutableURLRequest *request= [[[NSMutableURLRequest alloc] init] autorelease];
            [request setURL:[NSURL URLWithString:urlString]];
            [request setHTTPMethod:@"POST"];
            NSString *boundary = @"---------------------------14737809831466499882746641449";
            NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
            [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
            NSMutableData *postbody = [NSMutableData data];
            [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"xmlfile\"; filename=\"%@\"\r\n", [attributeDict objectForKey:@"url"]] dataUsingEncoding:NSUTF8StringEncoding]];
            [postbody appendData:[[NSString stringWithString:@"Content-Type: application/json\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
            NSData *filedata = [[NSFileManager defaultManager] contentsAtPath:filename];
            [postbody appendData:[NSData dataWithData:filedata]];
            [postbody appendData:[[NSString stringWithFormat:@"\r\n\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            [request setHTTPBody:postbody];
            
            NSString *aaa = [[NSString alloc] initWithData:postbody encoding:NSASCIIStringEncoding];
            //NSLog(@"%@", aaa);
            
            NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
            NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

            NSLog(@"RESPONSE : %@", returnString);
        }
    }  
}

#pragma mark HttpManagerDelegate
-(void)connectionDidFinish:(HttpManager*)aHttpManager {
	receivedData = httpManager.receivedData;
	NSLog(@"Working"); 
	//NSLog([[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]);
	
	// save it into sandbox
	NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSLog(@"%@", [dirArray objectAtIndex:0]);
	
	NSString *url = aHttpManager.url;
	NSArray *parts = [url componentsSeparatedByString:@"/"];
	NSString *filename = [parts objectAtIndex:[parts count]-1];
	
	NSLog(filename);
	if ([filename isEqualToString:@".DS_Store"]) {
		;
	}
	else {
		NSString *path = [NSString stringWithFormat:@"%@/%@", [dirArray objectAtIndex:0], filename];
		
		if ([receivedData writeToFile:path options:nil error:nil] == NO) {
			NSLog(@"writeToFile error");
		}
		else {
			NSLog(@"Written!");
		}
	};
}

-(void)connectionDidFail:(HttpManager*)aHttpManager {
	UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"Fail" message:@"Couldn't connect" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];
	//[alertView show];
}

-(void)connectionDidReceiveResponse:(NSURLResponse *)response {
	NSDictionary *responseHeaderFields;
	
	// 받은 header들을 dictionary형태로 받고
	responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields];	
	NSLog([responseHeaderFields description]);
	totalsize = [[responseHeaderFields objectForKey:@"Content-Length"] integerValue];
	NSLog(@"Header: %@", [responseHeaderFields objectForKey:@"Content-Length"]);
}

-(void)connectionDidReceiveData:(HttpManager*)aHttpManager {
	NSInteger currentLength = aHttpManager.receivedData.length;
//	NSLog(@"%i", aHttpManager.receivedData.length);
}

@end
